package com.itjeffrey.autocode.util;

import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

/**
 * Bean实体操作工具类
 */
public class BeanOprUtils {

    /**
     * Bean属性复制
     *
     * @param source 原Bean
     * @param target 目标Bean
     * @param <S>
     * @param <T>
     * @return
     */
    public static <S, T> T copyProperties(S source, T target) {
        BeanUtils.copyProperties(source, target);
        return target;
    }

    /**
     * Bean属性复制，支持BeanOprUtils.copyProperties(A, B::new)
     *
     * @param source 原Bean
     * @param target 目标Bean
     * @param <S>
     * @param <T>
     * @return
     */
    public static <S, T> T copyProperties(S source, Supplier<T> target) {
        T t = target.get();
        BeanUtils.copyProperties(source, t);
        return t;
    }

    public static <S, T> List<T> copyListProperties(List<S> s, Supplier<T> t){
        return copyListProperties(s, t, null);
    }

    /**
     * Bean集合的属性赋值，支持：BeanOprUtils.copyListProperties(A, B::new)
     *
     * @param source
     * @param target
     * @param <S>
     * @param <T>
     * @return
     */
    public static <S, T> List<T> copyListProperties(List<S> source, Supplier<T> target, BeanOprUtilsCallBack<S, T> beanOprUtilsCallBack) {
        Assert.notNull(source, "source is not allow to be null!");
        Assert.notNull(target, "target is not allow to be null!");
        List<T> targetList = new ArrayList<>(source.size());
        source.stream().forEach(s -> {
            T t = target.get();
            BeanUtils.copyProperties(s, t);
            targetList.add(t);
            if(beanOprUtilsCallBack != null){
                beanOprUtilsCallBack.callBack(s, t);
            }
        });
        return targetList;
    }
}
